<?php
/**
 * （材料）应用导入
 * User: bgl
 * Date: 2023/6/20
 * Time: 15:13
 */

namespace App\Admin\Controllers\Products;


use App\Importer\Basics\BImporter;
use App\Models\Product\ProductMaterialApplicationClassify;
use App\Util\RExcel;
use Encore\Admin\Controllers\AdminController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;
use Symfony\Component\HttpFoundation\File\UploadedFile;

class MaterialApplicationClassifyUploadController extends AdminController{

    protected $title = '应用品类上传';

    protected function grid(){
        $type = request('type');
        return view("products.material-application-classify.upload.index",compact('type'));
    }

    public function upload(Request $request){
        $file = $request->file('source_file');
        if ($file->isValid()) {
            $action = $request->get('action');
            $re = $this->{'_import'.$action}($file);
            if(is_array($re)) {
                if($re['flag']){
                    admin_toastr('文件：'.$re['data'].' 上传成功！');
                }else{
                    admin_toastr($re['data'],'error');
                }
            }else{
                return $re;
            }
        }else{
            admin_toastr('无效文件！','error');
        }
        return back()->withInput();
    }

    /**
     * 应用品类
     */
    private function _importApplicationClassify(UploadedFile $file){

        try{
            $data = Excel::toArray(new BImporter(),$file);
            $data = $data[0];
            if(!$data)return ['flag' => false,'data' => '请上传包含有数据的文件！'];

            $errors = [];
            $count = 1;
            foreach($data as $row){
                $count++;
                $_type = $row[0] ? trim($row[0]) : 0;
                $_code = $row[1] ? trim($row[1]) : '';
                $_titleCn = $row[2] ? trim($row[2]) : '';
                $_titleEn = $row[3] ? trim($row[3]) : '';


                if(!$_code || !$_titleCn || !$_titleEn){
                    $errors[$count] = ',必填项为空';
                    continue;
                }

                if (!in_array(intval($_type), ProductMaterialApplicationClassify::$applicationType)) {
                    $errors[$count] = $_type.',系统不存在';
                    continue;
                }

                $code = strtoupper($_code);
                if (!preg_match("/^[A-Z]{3}$/", $code)) {
                    $errors[$count] = ',应用品类代码(缩写)不正确，请填写三位大写字母';
                    continue;
                }
                $codeCount = ProductMaterialApplicationClassify::query()->where('code',$code)->count();
                if($codeCount > 0){
                    $errors[$count] = $_code.',系统已存在该应用品类代码(缩写)';
                    continue;
                }
                $titleCount = ProductMaterialApplicationClassify::query()->where('title',$_titleCn)->count();
                if($titleCount > 0){
                    $errors[$count] = $_titleCn.',系统已存在该应用品类名称';
                    continue;
                }

                //添加应用品类
                DB::beginTransaction();
                $classify = ProductMaterialApplicationClassify::query()
                    ->create([
                        'parent_id' => intval($_type) ?? 0,
                        'code' => $code,
                        'title' => $_titleCn,
                        'title_en' => $_titleEn,
                    ]);
                if(!$classify){
                    DB::rollBack();
                    continue;
                }
                DB::commit();
            }
            if(empty($errors)){
                return ['flag' => true,'data' => $file->getClientOriginalName()];
            }else{
                return RExcel::importResult($errors);
            }
        }catch(\Exception $e){
            report($e);
            return ['flag' => false,'data' => '系统异常！'];
        }
    }

    public function template(Request $request){
        $temp = $request->get('temp');
        $suffix = $request->get('suffix','xlsx');
        return Storage::disk('admin')->download("template/{$temp}-template.{$suffix}");
    }

}
